package com.hwh.bootdemoweb.Netty第六章;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author wenhao hu
 * @title: HelloServer
 * @projectName bootdemoweb
 * @description: TODO
 * @date 2021/12/1514:49
 */
public class HelloServer {
    /**
     * 服务器端代码
     * @param args
     */
    public static void main(String[] args) {
        //1.启动器 负责组装netty组件，启动服务器
        new ServerBootstrap()
                //2.添加eventLoop 组成(1.利用selector监测事件，2.线程)
                .group(new NioEventLoopGroup())
                //3.选择一个ServerSocketChannel实现
                .channel(NioServerSocketChannel.class)
                //4.设置worker(child)能干哪些事情(handler)
                .childHandler(
                        //5.代表和客户端进行数据读写的通道Initializer处死话，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>(){
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        //添加具体handler
                        ch.pipeline().addLast(new StringDecoder()); //将bytebuffer转换成字符串
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){ //自定义handler
                            @Override //读事件
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                //打印字符串
                                System.out.println(msg);
                            }
                        });
                    }
                })
                //6.绑定监听端口
                .bind(8080);
    }
}
